package com.pactera.utils;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.lang3.StringUtils;

public class XmlUtils {

    /**
     * xml转bean对象
     *
     * @author: EC_liqingdian
     * @Modify:
     * @Date: 2020/5/28
     */
    public static <T> T toBean(Class<T> clazz, String xml) {
        if (StringUtils.isBlank(xml)) {
            return null;
        }
        XStream xstream = new XStream();
        XStream.setupDefaultSecurity(xstream);
        xstream.allowTypesByRegExp(new String[]{".*"});
        xstream.processAnnotations(clazz);
        xstream.autodetectAnnotations(true);
        T xmlObject = (T) xstream.fromXML(xml);
        return xmlObject;
    }

    /**
     * bean转换成xml
     *
     * @author: EC_liqingdian
     * @Modify:
     * @Date: 2020/5/28
     */
    public static String toXml(Object obj) {
        if (obj == null) {
            return null;
        }
        XStream xstream = new XStream();
        XStream.setupDefaultSecurity(xstream);
        xstream.allowTypesByRegExp(new String[]{".*"});
        xstream.processAnnotations(obj.getClass());
        xstream.autodetectAnnotations(true);
        String xml = xstream.toXML(obj);
        return xml;
    }
}